<template>
  <div class="app-container">
    <!--<div class="filter-area">-->
    <div style="width: 220px;float: left;">
      <el-input placeholder="输入关键字进行过滤"
                v-model="filterText"
                style="margin-bottom: 10px;">
      </el-input>

      <div style="height: calc(100vh - 146px);width: 100%;" ref="officeArea">
        <happy-scroll resize size="8" ref="officeAreaScroll">
          <el-tree
            style="padding-right: 30px;"
            :data="officeTreeData"
            :props="defaultProps"
            node-key="classId"
            @node-click="nodeClick"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expand-all="true"
            ref="officeTree"
          ></el-tree>
        </happy-scroll>
      </div>
    </div>
    <!--</div>-->

    <!--<div style="float: right;width: calc(100% - 210px);">-->
    <div style="margin-left: 240px;">
      <div style="font-size: 24px;padding-bottom: 10px">{{checkedOffice.officeName}}</div>
      <div class="filter-container">
        <div class="filter-block">
          <span>姓名：</span>
          <el-input size="small" v-model="listQuery.realName" @keyup.enter.native="fetchData(true)"></el-input>
        </div>
        <div class="filter-block">
          <span>状态：</span>
          <el-select
            clearable
            size="small"
            v-model="listQuery.status"
            placeholder="请选择"
            filterable
            @change="fetchData(true)"
          >
            <el-option
              v-for="item in faceStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div class="filter-btn-area">
          <el-button size="small" type="primary" @click="fetchData(true)">查询</el-button>
          <el-button size="small" type="none" @click="initListQuery">清除</el-button>
        </div>


        <div class=" face-open-btn">
          <div>  共{{sysUserNum}}人，人脸下发成功<span style="color: #02b2b5">{{faceIssuedSuccessNum}}</span>人</div>
          <div>
            <el-button size="small" type="primary"
                       @click="batchUploadPhoto"
            >批量导入</el-button>
            <el-button size="small" type="primary" @click="deviceSync" > 设备同步</el-button>
          </div>
        </div>

      </div>

      <el-table :data="tableData" border highlight-current-row
                v-loading="tableLoading"
                style="width: 100%" ref="mainTable">
        <el-table-column label="头像" align="center">
          <template slot-scope="scope">
            <div
              @click.stop="getCheckId(scope.row)"
              @contextmenu="avatarMouseOver($event,scope.row)"
            >
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :show-file-list="false"
                name="filesToUpload[]"
                with-credentials
                :before-upload="beforePhotoUpload"
                :file-list="singleFileList"
                :on-change="singleFileListChange"
                :http-request="uploadPhotoByCheck"
                :auto-upload="false"

              >
                <el-tooltip
                  class="item"
                  effect="light"
                  placement="right"
                  v-if="scope.row.facePhoto"
                >
                  <div slot="content">
                    <img
                      v-if="scope.row.facePhoto"
                      :src="scope.row.facePhoto"
                      title="更新头像"
                      class="avatar"
                    />
                  </div>
                  <img
                    v-if="scope.row.facePhoto"
                    :src="scope.row.facePhoto"
                    title="更新头像"
                    class="avatar me-avatar"
                  />
                </el-tooltip>
                <!--<img v-if="userInfoForm.facePhoto" :src="userInfoForm.facePhoto" class="avatar">-->
                <i v-else class="el-icon-plus avatar-uploader-icon" title="上传头像"></i>
              </el-upload>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="realName" align="center"></el-table-column>
        <el-table-column label="唯一编号" prop="userId" align="center">
        </el-table-column>

        <!--<el-table-column label="唯一编号" align="center">-->
          <!--<template slot-scope="scope" failReason>-</template>-->
        <!--</el-table-column>-->




        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <span
              :style="formatFaceColor(parseInt(scope.row.faceStatus))"
            >{{formatFaceStatus(parseInt(scope.row.faceStatus))}}</span>
          </template>
        </el-table-column>


        <el-table-column label="失败原因" align="center">
          <template slot-scope="scope">
            <!--校验失败-->
            <span style="color: #f00;" v-if="scope.row.faceStatus == 3" >{{scope.row.failReason}}</span>
            <!--下发失败-->
            <span style="color: #f00;" v-else-if="scope.row.faceStatus == 5" >某些班牌端接收图片失败，请查看详细信息</span>
          </template>

        </el-table-column>

        <el-table-column label="详细导入状态" align="center">
          <template slot-scope="scope">
            <el-button size="small" v-if="scope.row.faceStatus != 0 && scope.row.faceStatus != 3" type="primary"  @click.stop="handleClickState(scope.row)">查询</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </div>
    <el-dialog :visible.sync="previewData.imgDialog" custom-class="preview-img">
      <img width="100%" :src="previewData.imgUrl" alt />
    </el-dialog>

    <el-dialog v-el-drag-dialog   :visible.sync="batchUpload.batchUploadDialog"
               width="82%" class="batchUploadDialog"
               @close="closeBatchUploadDialog"
               :close-on-click-modal="false"
               ref="batchUploadDialog"
    >
      <div slot="title" v-html="batchUpload.title">
      </div>
      <div style="width: 100%;margin: auto;min-height: 100px;">
        <div class="el-form-item">
          <div class="ele-form-content">
            <el-upload
              style="display: block"
              :multiple="true"
              class="upload-demo"
              ref="batchUpload"
              :action="batchUploadUrl"
              :accept="pictureTypeString"
              :data="{schoolId : schoolId}"
              :before-upload="beforeBatchUpload"
              list-type="picture-card"
              :on-success="handleBatchUploadSuccess"
              :on-change="batchFileListChange"
              :on-remove="handleBatchFileRemove"
              :file-list="batchFileList"
              :http-request="batchUploadFile"
              :auto-upload="false">
              <div class="batchUpload-button">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click.stop="batchUploadConfirm">开始上传</el-button>
              </div>
            </el-upload>
            <div ref="batchUploadFailList" style="display: none">
              <div v-for="(item, index) in batchUploadFailList" :key="index" >
                <div class="upload-file-item">错误原因: <span style="color: #F00;">{{formatBatchUploadErrorMsgByCode(item.errorMsg)}}   <span style="color: #000">共计:{{item.list.length}}</span></span></div>
                <div class="upload-file-list">
                  <div class="upload-file-list-item" v-for="(imgItem, itemIndex) in item.list" :key="itemIndex">
                    <div class="upload-file-list-item-img">
                      <img :src="imgItem.url" alt="">
                    </div>
                    <!--<div class="upload-file-list-item-studentNo" >唯一编号: {{formatStudentNoByPhotoName(imgItem.prove)}}</div>-->
                    <div class="upload-file-list-item-studentNo" >{{formatStudentNoByPhotoName(imgItem.prove)}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-dialog
        width="30%"
        title="上传文件内容有误"
        append-to-body>
      </el-dialog>
    </el-dialog>


    <el-dialog
      class="issued-status-dialog"
      :title="importStatusDialog.title"
      :visible.sync="importStatusDialog.showDialog"
      :close-on-click-modal="false"
      @close="closeImportStatusDialog"
    >
      <span>下发成功:{{issuedDetail.success}}&nbsp;&nbsp;下发中:{{issuedDetail.issuedIng}}&nbsp;&nbsp;下发失败:{{issuedDetail.fail}}</span>

      <div  v-loading="importStatusDialog.loading">
        <el-table
          :data="importStatusDialog.tableData"
          min-height="52vh"
          border
        >
          <el-table-column label="设备名称" prop="deviceName" align="center"></el-table-column>
          <el-table-column label="设备ID" prop="deviceId" align="center"></el-table-column>
          <el-table-column label="绑定场所" prop="bindPlace" align="center"></el-table-column>
          <el-table-column label="下发状态"  align="center">
            <template slot-scope="scope">
              <span  :style="formatIssuedColor(parseInt(scope.row.issuedStatus))">{{formatIssuedDetail(scope.row.issuedStatus)}}</span>
            </template>
          </el-table-column>
          <el-table-column    label="操作"  width="220" align="center" >
            <template slot-scope="scope">
              <el-button size="small" type="primary" v-if="scope.row.issuedStatus != 0 && scope.row.issuedStatus != 1 " @click.stop="handleClickRenew(scope.row)">重新下发</el-button>
            </template>
          </el-table-column>

        </el-table>
      </div>

      <el-dialog
        title="提示"
        style="width: 70vw;margin: 0 auto"
        :visible.sync="importStatusDialog.tipDialog"
        :close-on-click-modal="false"
        append-to-body>
        <div style="text-align: center">人脸库已下发，请耐心等待</div>
        <div slot="footer">
          <el-button size="small" class="dialog-close-btn" type="primary"  @click.stop="importStatusDialog.tipDialog = false">关闭</el-button>
        </div>
      </el-dialog>
      <div slot="footer">
        <el-button size="small"  class="dialog-close-btn" type="primary"  @click.stop="importStatusDialog.showDialog = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="提示"
      style="width: 70vw;margin: 0 auto"
      :visible.sync="tipDialog"
      :close-on-click-modal="false"
      @close="syncDialog"
    >
      <div style="text-align: center">已开始更新，请耐心等待几分钟后，刷新页面查看各个用户的更新状态</div>
      <div slot="footer">
        <el-button size="small" class="dialog-close-btn" type="primary"  @click.stop="tipDialog = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllOffice, listAllOfficeUser, updateFacePhoto, getUserFaceIssuedStatus, deviceSync, rnewIssuedFace, saveFaceCheckResult, savePhotoCheckResult, reissueUserDevice } from '@/api/api'
import { officeArrayToTreeWithOfficeType } from '@/utils/utils'
import waves from '@/directive/waves'
import elDragDialog from '@/directive/el-dragDialog'
import  HappyScroll  from '@/components/vuescroll/vue-scroll.vue'
import { mapGetters } from 'vuex'
import defaultSettings from '@/settings'
export default {
  directives: {
    waves,elDragDialog
  },
  components: {
    HappyScroll
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  data() {
    return {
      //文件上传相关
      pictureType: [
        'image/gif',
        'image/jpeg',
        'image/jpg',
        'image/bmp',
        'image/png',
        'gif',
        'jpeg',
        'jpg',
        'png',
        'image'
      ],
      // 单个上传文件的List
      singleFileList : [],
      // uploadImgUrl: process.env.VUE_APP_PMS_API + '/busi/upload/img?code=1',
      // uploadImgUrl: process.env.VUE_APP_CHECK_FACE,
      uploadImgUrl: `${process.env.VUE_APP_CURRENT_DOMAIN_NAME}/checkPhoto`,
      tableData: [],
      tableLoading: false,
      pageInfo: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      /*** 图片预览相关    ***/
      previewData: {
        imgDialog: false,
        imgUrl: ''
      },
      buttonType: '',
      faceStatusList: [
        { label: '全部', value: null },
        { label: '未上传', value: 0 },
        { label: '有设备未下发', value: 2 },
        { label: '检验失败', value: 3 },
        { label: '成功', value: 4 },
        { label: '下发失败', value: 5 },
        { label: '下发中', value: 6 },
      ],
      issuedStatusList: [
        {label: '下发失败：其他错误', value: -1},
        {label: '下发成功', value: 0},
        {label: '下发中', value: 1},
        {label: '未下发', value: 2},
        {label: '下发失败：人脸图片模糊', value: 3},
        {label: '下发失败：其他', value: 4},
      ],
      listQuery: {
        username: '',
        realName: '',
        roleId: '',
        status: ''
      },
      userInfoForm: {
        userId: '',
        facePhoto: ''
      },
      schoolId: sessionStorage.getItem('schoolId'),

      defaultProps: {
        children: 'children',
        label: 'officeName'
      },
      officeTreeData: [],
      checkedOffice: {},
      filterText: '',
      /** 批量上传图片相关 **/
      batchUpload: {
        title: '',
        batchUploadDialog: false
      },
      batchFileList : [],
      batchUploadFailList : [],
      batchUploadSuccessList : [],
      batchUploadUrl:  '',
      pictureTypeString: "image/*",
      batchFileList : [],
      loading: {},
      /** 批量上传图片相关结束 **/
      /** 人脸下发设备详情  **/
      importStatusDialog: {
        showDialog : false,
        title: '人脸库下发详情',
        tableData: [],
        tipDialog: false,
        loading: false
      },
      tipDialog: false,
      currentUserId: '',
      currentUserName: '',
      // 当前记录id
      currentRecordId: '',
      issuedDetail: {
        success : 0,
        issuedIng: 0,
        fail: 0,
      },
      issuedCount: {
        success: '',
        total: '',
      },
      /** 人脸下发设备详情结束  **/
      sysUserNum : 0,
      faceIssuedSuccessNum : 0,
      // 调用第三方图片校验结果
      checkPhotoResultList: []

    }
  },

  methods: {
    /*** 图片上传相关 ***/
    handlePhotoSuccess(res, file) {
      // this.userInfoForm.facePhoto = res.result
      // this.saveUserInfo(this.userInfoForm.userId, this.userInfoForm.facePhoto)
      let failReason = null
      let checkResult = null
      let facePhoto = null;


      if (res.code == 200 ) {
        let r = res.data[0]
        if (r.face_check_ok == true){
          checkResult = 2
          facePhoto = r.face_path
        } else {
          failReason = r.face_check_msg;
          checkResult = 3
          facePhoto = r.origin_path
        }

        let params = {
          schoolId : sessionStorage.getItem('schoolId'),
          officeId : this.checkedOffice.id,
          userId :  this.userInfoForm.userId,
          facePhoto : facePhoto,
          failReason : failReason,
          checkResult : checkResult
        }
        updateFacePhoto(params).then(res => {
          if (res.code == 200) {
            this.fetchData(false)
          } else {
            this.$alert("图片错误！" + res.message, "错误", {type : "error"})
          }
        })
      } else {
        this.$alert("人脸校验服务异常！" + res.data.msg, "错误", {type : "error"})
      }


    },
    beforePhotoUpload(file) {
      const isPicture = this.pictureType.indexOf(file.type) !== -1
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isPicture) {
        this.$alert('只能上传图片!', '提示', { type: 'warning' })
      }
      if (!isLt2M) {
        this.$alert('上传照片大小不能超过 10MB!', '提示', { type: 'warning' })
      }
      return isPicture && isLt2M
    },
    /*** 图片预览相关    ***/
    initListQuery() {
      this.listQuery = {
        username: '',
        realName: '',
        roleId: '',
        status: ''
      }
      this.fetchData(true)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.officeName.indexOf(value) !== -1
    },
    initPageInfo() {
      this.pageInfo.pageNum = 1
    },
    fetchData(initPageInfo) {
      this.tableData = []
      if (initPageInfo) {
        this.initPageInfo()
      }
      let params = {
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
        officeId: this.checkedOffice.id,
        schoolId: sessionStorage.getItem('schoolId'),
        realName: this.listQuery.realName,
        status: this.listQuery.status
      }
      this.tableLoading = true
      listAllOfficeUser(params).then(res => {
        if (res.code === 200) {
          this.tableData = []
          this.tableData = res.result && res.result.page && res.result.page.list ? res.result.page.list : []
          this.pageInfo.total = res.result && res.result.page && res.result.page.total ?   res.result.page.total : 0
          this.faceIssuedSuccessNum = res.result && res.result.faceIssuedSuccessNum ? res.result.faceIssuedSuccessNum : 0
          this.sysUserNum = res.result && res.result.sysUserNum ? res.result.sysUserNum : 0
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.tableLoading = false
      })
      // officeUserScopeList(param).then((res) => {
      //   if (res.code === 200) {
      //     this.tableData = res.result && res.result.list ? res.result.list : [];
      //     this.pageInfo.total = res.result.total;
      //   } else {
      //     this.$message.error(res.message);
      //   }
      // })
    },

    handleSizeChange(val) {
      this.pageInfo.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val
      this.fetchData()
    },
    getSchoolList() {
      listAllOffice({ schoolId: sessionStorage.getItem('schoolId') }).then(
        res => {
          if (res.code == 200) {
            if (res.result && res.result.length && res.result.length > 0) {
              this.checkedOffice = res.result[0]
              this.officeTreeData = res.result
              this.fetchData(true)
            }
          } else {
            this.officeTreeData = []
          }
        }
      )
    },
    nodeClick(item) {
      this.tableData = []
      if (!item.id) {
        this.pageInfo = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        return false
      }
      this.checkedOffice = item
      this.fetchData(true)
    },
    formatFaceColor(code) {
      if (code == 0) {
        return 'color: #33333'
      }else if (code == 1 || code == 4) {
        return 'color: #67C23A'
      } else if (code == 2) {
        return 'color: #f67d00'
      } else if (code == 3 || code == 5) {
        return 'color: #FF0000'
      } else if(code  == 6) {
        return 'color: #409EFF'
      }
      return 'color: #333333'
    },
    formatFaceStatus(code) {
      for (let item of this.faceStatusList) {
        if (item.value == code) {
          return item.label
        }
      }
      return null
    },
    formatResultMenu(code) {
      switch (code) {
        case 0:
          return (this.buttonType = 'info')
        case 1:
          return (this.buttonType = 'success')
        case 2:
          return (this.buttonType = 'warning')
        case 3:
          return (this.buttonType = 'danger')
        default:
          return (this.buttonType = 'info')
      }
    },
    //图片上传成功后保存用户信息
    saveUserInfo(userId, facePhoto) {
      let params = {
        schoolId: sessionStorage.getItem('schoolId'),
        officeId: this.checkedOffice.id,
        userId,
        facePhoto
      }
      updateFacePhoto(params).then(res => {
        if (res.code == 200) {
          this.fetchData(false)
        }
      })
    },
    getCheckId(data) {
      this.userInfoForm.userId = data.userId
    },

    /***** 图片批量导入相关  *****/
    openFullScreen() {
      this.loading = {}
      this.loading = this.$loading({
        lock: true,
        text: '图片上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    // 通过第三方校验结果格式化图片上传失败信息
    formatUploadFailListByCheckPhoto() {
      if (this.batchUploadFailList.length > 0 && this.checkPhotoResultList.length > 0 ) {
        this.batchUploadFailList.forEach(listItem => {
          if (listItem.list.length > 0) {
            listItem.list.forEach(item => {
              for (let checkItem of this.checkPhotoResultList) {
                if (checkItem.file_name == item.userNo) {
                  item.url = checkItem.origin_path
                  item.prove = item.userNo
                  break;
                }
              }
            } )
          }
        })
      }
    },

    formatUploadFailList() {
      if(this.batchFileList.length > 0) {
        this.batchFileList.forEach(item => {
          if (item.name != undefined) {
            if (this.batchUploadFailList.length > 0) {
              let tempName = this.formatStudentNoByPhotoName(item.name)
              this.batchUploadFailList.forEach(failItem => {
                if(failItem != undefined && failItem.list.length > 0) {
                  failItem.list.forEach(obj => {
                    if(obj.prove != undefined && obj.prove == tempName) {
                      obj.url = item.url
                    }
                  })
                }
              })
            }
          }
        })
      }
    },
    batchUploadPhoto() {
      // this.batchUpload.title = this.checkedOffice.officeName != null ? this.checkedOffice.officeName+"  批量导入"  : "批量导入";
      this.batchUpload.title = `${defaultSettings.batchTitle} `
      this.batchUpload.batchUploadDialog = true;
      this.$nextTick(() => {
        this.$refs.batchUpload.$el.style.display = "block"
        this.$refs.batchUploadFailList.style.display = "none"
      })

    },


    validateIsPicture(file) {
      if (file.type ) {
        return this.pictureType.indexOf(file.type) !== -1
      }
    },
    validateIsLt10M(file) {
      if (file.size ) {
        return   file.size / 1024 / 1024 < 2
      }
    },
    closeBatchUploadDialog() {
      this.batchFileList = []
      this.batchUploadFailList = []
      this.batchUploadSuccessList = []
    },
    beforeBatchUpload(file, fileList) {

    },
    handleBatchUploadSuccess() {

    },
    batchFileListChange(file, fileList) {


      //过滤重复文件
      let filterFileList =  fileList.filter((fileItem, index, self) => {
        //存放文件名称的数组
        let fileNameList = []
        fileList.forEach(fileTemp => {
          if(fileTemp.name != undefined) {
            fileNameList.push(fileTemp.name);
          }
        })
        return fileNameList.indexOf(fileItem.name) === index ;
      })
      this.batchFileList = filterFileList
    },
    handleBatchFileRemove(file, fileList) {
      this.batchFileList = fileList
    },
    //通过第三方接口校验图片后批量保存
    batchSaveByCheckPhoto() {
      if(this.batchFileList == undefined || this.batchFileList.length == 0) {
        this.$message.warning("请选择文件")
        return
      }

      let formData = new FormData;
      if(this.batchFileList != null && this.batchFileList != "" && this.batchFileList != []) {
        this.batchFileList.map(file => {
          formData.append('filesToUpload[]', file.raw);
        })
      }
      let classId = sessionStorage.getItem("schoolId");
      formData.append("officeId", classId);
      formData.append("schoolToken", sessionStorage.getItem("schoolId"));
      // 图片校验

      let uploadFlag = true
      let photoTypeErrorList = ""
      let photoSizeErrorList = ""
      this.batchFileList.forEach(item => {
        let sizeFlag = this.validateIsLt10M(item)
        if(sizeFlag == false) {
          photoSizeErrorList = photoSizeErrorList === "" ?   item.name : photoSizeErrorList + "  " + item.name;
          uploadFlag = false
        }
        let typeFlag = this.validateIsPicture(item)
        if (typeFlag == false) {
          photoTypeErrorList = photoTypeErrorList + item.name;
          uploadFlag = false
        }
      })
      if (photoSizeErrorList != "") {
        this.$message.warning(`${photoSizeErrorList}图片大小超过限制`)
      }

      if (!uploadFlag) {
        return ;
      }
      this.openFullScreen()
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.$axios.post(process.env.VUE_APP_CHECK_FACE, formData, config).then(res => {
        if (res.data.code == 200) {

          this.checkPhotoResultList = res.data.data

          let faceCheckResultStr =  JSON.stringify(res.data.data)

          let params = {
            faceCheckResultStr
          }
          //将保存结果入库
          savePhotoCheckResult(params).then(res => {
            if (res.code == 200) {
              this.batchUploadFailList = []
              this.batchUploadSuccessList = []
              this.batchUploadSuccessList = res.result && res.result.successList ?  res.result.successList : []
              // this.batchUploadFailList = res.data.result && res.data.result.errorList ?  res.data.result.errorList : []
              let tempUploadFailList = res.result && res.result.errorList ?  res.result.errorList : []
              if (tempUploadFailList.length > 0) {
                let tempArr =  this.groupBy(tempUploadFailList, item => item.code);
                tempArr.forEach(item => {
                  if(item.length != undefined && item.length > 0) {
                    let tempObj = {}
                    tempObj.errorMsg = item[0].code
                    tempObj.list = item
                    this.batchUploadFailList.push(tempObj)
                  }
                })
                // console.log(this.batchUploadFailList)

                this.formatUploadFailListByCheckPhoto()
                // console.log(this.batchUploadFailList)
                // this.batchUploadFailList.forEach(item => console.log(item))
                //this.batchUpload.title = this.batchUpload.title + "结果" + ` <span class='batchUpload-success '>成功: ${this.batchUploadSuccessList.length}</span>  `+ `  <span class='batchUpload-fail'>失败: ${tempUploadFailList.length}</span>`

                this.batchUpload.title =  `${defaultSettings.batchTitle}结果   <span class='batchUpload-success '>成功: ${this.batchUploadSuccessList.length}</span>  `+ `  <span class='batchUpload-fail'>失败: ${tempUploadFailList.length}</span>`

                this.$refs.batchUpload.$el.style.display = "none"
                this.$refs.batchUploadFailList.style.display = "block"
              } else {
                this.batchUploadFailList = []
                this.batchUpload.title = ''
                this.batchUpload.batchUploadDialog = false
              }
              this.fetchData(true)
              this.loading.close();
              if (tempUploadFailList.length == 0) {
                this.$message.success("批量导入成功!")
              }
            } else  {
              this.$message.error(res.message)
              this.loading.close();
              this.batchUploadFailList = []
              this.batchUpload.title = ''
              this.batchUpload.batchUploadDialog = false
            }
          })

        } else {
          this.$message.error("图片剪裁校验服务异常！")
          this.loading.close();
          this.batchUploadFailList = []
          this.batchUpload.title = ''
          this.batchUpload.batchUploadDialog = false
        }

      })


    },
    singleFileListChange(file, fileList) {
// console.log(file)
      const isPicture = this.pictureType.indexOf(file.raw.type) !== -1
      const isLt2M = file.size / 1024 / 1024 < 10

      if (!isPicture) {
        this.$alert('只能上传图片!', '提示', { type: 'warning' })
        return
      }
      if (!isLt2M) {
        this.$alert('上传照片大小不能超过 10MB!', '提示', { type: 'warning' })
        return
      }

      this.singleFileList.push(file)
      this.uploadPhotoByCheck()
    },
    // 调用第三方校验接口后保存结果(单个上传校验)
    uploadPhotoByCheck() {

      if (this.singleFileList.length > 0) {
        let file = this.singleFileList[0]
        let formData = new FormData;
        formData.append('filesToUpload[]', file.raw)
        let classId = sessionStorage.getItem("schoolId");
        formData.append("officeId", classId);
        formData.append("schoolToken", sessionStorage.getItem("schoolId"));
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        this.$axios.post(process.env.VUE_APP_CHECK_FACE, formData, config).then(res => {
          if (res.data.code == 200) {
            let failReason = null
            let checkResult = null
            let facePhoto = null;

            let r = res.data.data[0]
            if (r.face_check_ok == true){
              checkResult = 2
              facePhoto = r.face_path
            } else {
              failReason = r.face_check_msg;
              checkResult = 3
              facePhoto = r.origin_path
            }
            let params = {
              schoolId : sessionStorage.getItem('schoolId'),
              officeId : this.checkedOffice.id,
              userId :  this.userInfoForm.userId,
              facePhoto : facePhoto,
              failReason : failReason,
              checkResult : checkResult
            }
            updateFacePhoto(params).then(res => {
              if (res.code == 200) {
                this.fetchData(false)
              } else {
                this.$alert("图片错误！" + res.message, "错误", {type : "error"})
              }
            }).finally(() => this.singleFileList = [])
          } else {
            this.$message.error("图片剪裁校验服务异常！")
            this.singleFileList = []
          }
        })


      }

    },

  // 通过调用后台接口直接批量保存
    batchUploadFile (file) {
      if(this.batchFileList == undefined || this.batchFileList.length == 0) {
        this.$message.warning("请选择文件")
        return
      }

      let formData = new FormData;
      if(this.batchFileList != null && this.batchFileList != "" && this.batchFileList != []) {
        this.batchFileList.map(file => {
          formData.append('files', file.raw);
        })
      }
      let classId = sessionStorage.getItem("schoolId");
      formData.append("officeId", classId);
      formData.append("schoolId", sessionStorage.getItem("schoolId"));
      formData.append("type", 0);
      // 图片校验

      let uploadFlag = true
      let photoTypeErrorList = ""
      let photoSizeErrorList = ""
      this.batchFileList.forEach(item => {
        let sizeFlag = this.validateIsLt10M(item)
        if(sizeFlag == false) {
          photoSizeErrorList = photoSizeErrorList === "" ?   item.name : photoSizeErrorList + "  " + item.name;
          uploadFlag = false
        }
        let typeFlag = this.validateIsPicture(item)
        if (typeFlag == false) {
          photoTypeErrorList = photoTypeErrorList + item.name;
          uploadFlag = false
        }
      })
      if (photoSizeErrorList != "") {
        this.$message.warning(`${photoSizeErrorList}图片大小超过限制`)
      }

      if (!uploadFlag) {
        return ;
      }
      this.openFullScreen()
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }

      this.$axios.post(process.env.VUE_APP_BASE_API+`/pub/upload/batchFaceUpload`,formData, config).then(res=>{
        if(res.data.code &&  res.data.code === 200) {
          // this.batchFileList = []
          this.batchUploadFailList = []
          this.batchUploadSuccessList = []
          this.batchUploadSuccessList = res.data.result && res.data.result.successList ?  res.data.result.successList : []
          // this.batchUploadFailList = res.data.result && res.data.result.errorList ?  res.data.result.errorList : []
          let tempUploadFailList = res.data.result && res.data.result.errorList ?  res.data.result.errorList : []
          if (tempUploadFailList.length > 0) {
            let tempArr =  this.groupBy(tempUploadFailList, item => item.code);
            tempArr.forEach(item => {
              if(item.length != undefined && item.length > 0) {
                let tempObj = {}
                tempObj.errorMsg = item[0].code
                tempObj.list = item
                this.batchUploadFailList.push(tempObj)
              }
            })
            this.formatUploadFailList()
            // this.batchUploadFailList.forEach(item => console.log(item))
            //this.batchUpload.title = this.batchUpload.title + "结果" + ` <span class='batchUpload-success '>成功: ${this.batchUploadSuccessList.length}</span>  `+ `  <span class='batchUpload-fail'>失败: ${tempUploadFailList.length}</span>`

            this.batchUpload.title =  `${defaultSettings.batchTitle}结果   <span class='batchUpload-success '>成功: ${this.batchUploadSuccessList.length}</span>  `+ `  <span class='batchUpload-fail'>失败: ${tempUploadFailList.length}</span>`

            this.$refs.batchUpload.$el.style.display = "none"
            this.$refs.batchUploadFailList.style.display = "block"
          } else {
            this.batchUploadFailList = []
            this.batchUpload.title = ''
            this.batchUpload.batchUploadDialog = false
          }
          this.fetchData(true)
          this.loading.close();
          if (tempUploadFailList.length == 0) {
            this.$message.success("批量导入成功!")
          }
        } else {
          this.loading.close();
          this.batchUploadFailList = []
          this.batchUpload.title = ''
          this.batchUpload.batchUploadDialog = false
          this.$message.warning(res.data.message)
        }
      })
    },
    batchUploadConfirm () {
      this.batchSaveByCheckPhoto();
    },

    formatBatchUploadErrorMsgByCode(code) {
      if (code === -1) {
        return "找不到该用户"
      } else if (code === 2) {
        return "未检测到人脸特征"
      } else {
        return "系统错误"
      }
    },
    //将图片名称转化为唯一编号
    formatStudentNoByPhotoName(photoName) {
      if (photoName == null) {
        return ""
      } else {
        let flagIndex = photoName.lastIndexOf('.');
        if (flagIndex >= 0) {
          let studentNoTemp = photoName.substring(0, flagIndex);
          return studentNoTemp;
        } else {
          return photoName
        }
      }
    },

    groupBy(array, f) {
      let groups = {};
      array.forEach(function (o) {
        let group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
      });
      return Object.keys(groups).map(function (group) {
        return groups[group];
      });
    },
      /***** 图片批量导入相关结束  *****/
      refreshOfficeChooseView() {
        let self = this;
        let rightHeight = this.$refs.mainTable.$el.scrollHeight + 187;
        let vhHeight = document.body.clientHeight;
        let newOfficeHeight = (rightHeight > vhHeight ? rightHeight : vhHeight) - 146;
        self.$refs.officeArea.style.height = newOfficeHeight + "px";
        self.$refs.officeAreaScroll.initSize.height = newOfficeHeight + "px";
        self.$refs.officeAreaScroll.computeStripY();

      },
      /****  人脸下发至设备详情   ****/
      handleClickState(data) {
        if (!data) {
          return
        }
        this.currentUserId = data.userId || ''
        this.currentUserName = data.realName || ''
        this.currentRecordId = data.id || ''
        let params  = {
          userId : data.userId,
          schoolId : this.schoolId
        }
        this.importStatusDialog.tableData = []
        this.importStatusDialog.showDialog = true
        this.importStatusDialog.loading = true
        getUserFaceIssuedStatus(params).then(res => {
          if (res.code == 200) {
            this.importStatusDialog.title = `${data.realName}人脸库下发详情`
            // console.log("------------------")
            // console.log(res.result)

            this.importStatusDialog.tableData =this.metamorphosisSort(res.result)|| []
            // console.log("-------------------")
            // console.log( this.importStatusDialog.tableData)
            // this.importStatusDialog.tableData =  this.importStatusDialog.tableData.concat( this.importStatusDialog.tableData)
          } else {
            this.$message.error(res.message);
            this.importStatusDialog.showDialog = false
          }
        }).finally(() => {
          this.importStatusDialog.loading = false
        })
      },


    // 排序
    metamorphosisSort(list) {
      if (list.length == undefined || list.length == 0) {
        return list;
      }
      let res = [];
      let tempArr = []
      tempArr =   list.filter(item =>  item.issuedStatus == 2);
      res = [...res, ...tempArr]
      tempArr =   list.filter(item =>  item.issuedStatus == 3 || item.issuedStatus == 4 || item.issuedStatus == -1);
      this.issuedDetail.fail = tempArr.length
      res = [...res, ...tempArr]
      tempArr =   list.filter(item => item.issuedStatus == 1);
      this.issuedDetail.issuedIng = tempArr.length
      res = [...res, ...tempArr]
      tempArr =   list.filter(item =>  item.issuedStatus == 0);
      this.issuedDetail.success = tempArr.length
      res = [...res, ...tempArr]

      return res;
    },
    formatIssuedColor(code) {
      if (code == 0) {
        return 'color:#67C23A'
      } else if (code == 1) {
        return 'color: #409EFF'
      }  else if (code == 2) {
        return 'color: #333333'
      }  else if (code == -1) {
        return 'color: #f00'
      }else {
        return 'color: #ff0000'
      }
    },
    formatIssuedDetail(code) {
      // console.log('code' + code)
      for (let item of this.issuedStatusList) {
        if (item.value == code) {
          return item.label
        }
      }
      return ""
    },
    closeImportStatusDialog() {
      // this.fetchData()
    },
    handleClickRenew(data) {
      this.fetchData(true)

      let params = {
        deviceId : data.deviceId,
        userId : this.currentUserId,
        recordId : this.currentRecordId,
        schoolId : sessionStorage.getItem("schoolId"),
        message : null
      }
      reissueUserDevice(params).then(res => {
        if (res.code == 200) {
          this.importStatusDialog.tipDialog = true;
          let params = {
            userId : this.currentUserId,
            schoolId : this.schoolId,
            realName : this.currentUserName
          }
          this.handleClickState(params)
        } else {
          this.$message.error(res.message)
        }
      })
    },


      /****  人脸下发至设备详情结束   ****/
      /****  设备同步开始   ****/
      deviceSync() {
        let params = {
          schoolId : this.schoolId
        }
        deviceSync(params).then(res => {
          if (res.code == 200) {
            this.tipDialog = true
            this.listQuery.realName = null
            this.listQuery.status = null
            this.fetchData(true)
          } else {
            this.$message.error(res.result)
          }
        })
      },
    syncDialog() {
      this.fetchData(true)
    },

    /****  设备同步结束   ****/

  },
  created() {
    this.getSchoolList()
  },
  mounted() {
    // console.log("this", this.$refs.officeAreaScroll)
  },
  watch: {
    filterText(val) {
      this.$refs.officeTree.filter(val)
    },
    // 'tableData.length' : function (newVal) {
    //   let self = this;
    //   this.$refs.mainTable.$nextTick(function () {
    //     self.refreshOfficeChooseView();
    //   });
    // }
  }
}
</script>
<style scoped lang="scss">
.me-avatar {
  width: 75px;
  height: 100px;
}
.avatar-uploader-icon {
  width: 75px;
  height: 100px;
  line-height: 100px;
}
.avatar-uploader-icon {
  font-size: 40px;
}
.filter-area {
  height: 800px;
  width: 200px;
  float: left;
  overflow-y: auto;
  &::after {
    content: '';
    display: block;
    clear: both;
  }
}

.upload-file-list {
  display: flex;
  flex-direction: row;
  flex-flow: wrap;
  &-item {
    width: 110px;
    height: 178px;
    margin: 0 40px 20px 0;
    display: flex;
    flex-direction: column;
    &-img {
      width: 110px;
      height: 148px;
      border: 1px solid #999999;
      border-radius: 4px;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
      }
    }

    &-studentNo {
      margin-top: 4px;
      width: 110px;
      height: 30px;
      line-height: 20px;
      /*text-align: center;*/
      /*overflow: auto;*/
      /*white-space:nowrap;*/
      /*text-overflow:ellipsis;*/
    }
    /*&-studentNo:hover {*/
      /*height: unset;*/
      /*overflow: auto;*/
      /*white-space: unset;*/
      /*text-overflow: unset;*/
      /*line-height: unset;*/
      /*z-index: 999 !important;*/
    /*}*/
    &-errorMsg {
      position: absolute;
      color: #f00;
      width: 148px;
      text-align: center;
    }
  }
}
</style>
